<template>
  <div class="flexContent">
    <!-- 新增入库 -->
    <h3>入库信息</h3>
    <el-form ref="ruleForm" :disabled="detail.isDetail" :model="sform" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="供应商：" prop="supplierId">
            <el-select v-if="!detail.isDetail" v-model="sform.supplierId" clearable placeholder="请选择供应商"
              style="width: 80%" popper-class="eloption" filterable @change="supplierChange" @click.native="getSCMList">
              <el-option v-for="item in firstSupplierList" :key="item.id" :value="item.id" :label="item.name" />
            </el-select>
            <span v-if="detail.isDetail">{{
              sform.supplierName ? sform.supplierName : "-"
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="上架仓库：" prop="warehouseName">
            <span>{{ sform.warehouseName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="收货备注：">
            <span>{{ sform.takeRemake ? sform.takeRemake : "无" }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16" :offset="0">
          <el-form-item label="备注：">
            <el-input v-clearEmoji v-if="!detail.isDetail" v-model.trim="sform.remake" placeholder="最多输入50个字符"
              maxlength="50" show-word-limit style="width: 80%" />
            <span v-if="detail.isDetail">{{
              sform.remake ? sform.remake : "-"
            }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item v-show="detail.isDetail" label="入库单号：">
            <!-- <el-input v-clearEmoji v-model="sform.remake" placeholder="最多输入50个字符" maxlength="50" show-word-limit style="width: 80%;" /> -->
            <span>{{ sform.number }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="add">
      <el-button class="addBtn" v-show="!detail.isDetail" @click="submitForm('ruleForm')">调订单</el-button>
    </div>
    <div class="table">
      <el-form ref="formData" :model="formData">
        <el-table border class="tablebox" :data="formData.tableData" max-height="510" style="width: 100%" size="medium">
          <el-table-column align="center" type="index" label="序号" width="80" />
          <el-table-column align="center" prop="name" :min-width="elTableAdaptationWidth('name', formData.tableData)"
            label="商品名称" />
          <el-table-column align="center" prop="firstCode"
            :min-width="elTableAdaptationWidth('firstCode', formData.tableData)" label="商品条码" />
          <!-- <el-table-column align="center" prop="mnemonic" :min-width="elTableAdaptationWidth('mnemonic', formData.tableData)"
            label="助记符" /> -->
          <!-- <el-table-column align="center" prop="firstCode" label="商品条码" width="150"
            :min-width="elTableAdaptationWidth('firstCode', formData.tableData)" /> -->
          <el-table-column align="center" prop="standard" label="规格" />
          <el-table-column align="center" prop="unitName" label="单位" />
          <el-table-column align="center" prop="agreedPrice" label="进价（元）" min-width="120"/>
          <el-table-column align="center" prop="regionName" label="区域">
            <template v-slot="{ row }">
              {{ row.regionName ? row.regionName : "-" }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="positionId" label="仓位">
            <template slot-scope="scope">
              <el-form-item v-if="!detail.isDetail" :prop="'tableData.' + scope.$index + '.positionId'"
                :rules="tableRules.positionId">
                <el-select ref="inputaldQty" v-model="scope.row.positionId" placeholder="" popper-class="eloption"
                  size="small" style="width: 100%" clearable filterable
                  @click.native="getPositonList(scope.row, scope.$index)"
                  @change="selectPositionId(scope.row, scope.$index)">
                  <el-option v-for="item in scope.row.positionList" :key="item.id" :value="item.id" :label="item.name" />
                </el-select>
              </el-form-item>
              <span v-if="detail.isDetail">{{ scope.row.positionName }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" :prop="detail.isDetail ? 'inboundCount' : 'takeCount'" label="入库数量"
            :min-width="120" />
          <el-table-column align="center" :prop="detail.isDetail ? 'inboundPiece' : 'takePiece'" label="入库件数"
            :min-width="120" />
          <el-table-column v-if="detail.isDetail" align="center" prop="batchNumber"
            :min-width="elTableAdaptationWidth('batchNumber', formData.tableData)" label="批次号" />
          <el-table-column align="center" prop="producer" label="产地" />
        </el-table>
      </el-form>
    </div>
    <div class="returnBtn">
      <el-button class="celBtn" v-if="!detail.isDetail" @click="cancelBtn">取消</el-button>
      <el-button class="celBtn" v-if="detail.isDetail" @click="cancelBtn">返回</el-button>
      <el-button class="addBtn" v-if="!detail.isDetail" @click="submitData('formData')">确定</el-button>
    </div>
    <el-dialog title="调收货单" :visible.sync="dialogTableVisible">
      <h3>调收货单</h3>
      <el-table border @current-change="showRow" highlight-current-row :data="gridData1" class="tablebox" height="202px"
        size="medium">
        <el-table-column label="序号" width="80" align="center">
          <template scope="scope">
            <el-radio v-model="radio" class="radio" :label="scope.$index"><span @click.native.stop>{{ scope.$index + 1
            }}</span></el-radio>
          </template>
        </el-table-column>
        <el-table-column property="number" align="center" label="收货编号" />
        <el-table-column property="takeTime" align="center" label="收货时间">
          <template v-slot="{ row }">
            <span>{{ row.takeTime | parseTime("YYYY-MM-DD") }}</span>
          </template>
        </el-table-column>
      </el-table>
      <h3 style="padding-top: 30px">收货单明细</h3>
      <el-table border :data="gridData2" class="tablebox" height="202px" size="medium">
        <el-table-column type="index" align="center" label="序号" width="80" />
        <el-table-column property="name" align="center" label="商品名称"
          :min-width="elTableAdaptationWidth('name', gridData2)" />
        <el-table-column property="firstCode" align="center" label="商品条码" />
        <el-table-column property="standard" align="center" label="规格" />
        <el-table-column property="unitName" align="center" label="单位" />
        <el-table-column property="producer" align="center" label="产地"
          :min-width="elTableAdaptationWidth('producer', gridData2)" />
        <el-table-column property="takeCount" align="center" label="收货数量" />
        <el-table-column property="takePiece" align="center" label="收货件数" />
      </el-table>
      <div slot="footer">
        <el-button class="celBtn" @click="cancelFn">取消</el-button>
        <el-button class="addBtn" @click="confirmFn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getReceivingOrderListBySupplier,
  selectDeliveryDetails,
  addInboundRecord,
  getInboundRecordDetail,
  selectForInbound,
} from "@/api/warehouse";
import { getSCMList } from "@/api/scm";
export default {
  name: "ReceivingAdd",
  data() {
    return {
      dialogTableVisible: false,
      firstSupplierList: [],
      sform: {
        supplierId: "",
        remake: "", // 备注
        warehouseName: "",
        takeRemake: "",
        warehouseId: "",
        detailsList: [],
        buyOrderId: "",
        takeDeliveryId: "",
        number: "",
        supplierName: "",
      },
      rules: {
        supplierId: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],
      },
      formData: {
        takeRemake: "",
        warehouseName: "",
        warehouseId: "",
        tableData: [],
      },
      positionList: [],
      tableRules: {
        positionId: [{ required: true, message: "仓位不能为空" }],
      },
      gridData1: [],
      gridData2: [],
      selected: {},
      radio: "",
      detail: {
        isDetail: false,
        id: "",
      },
      disabledList: [],
    };
  },
  created() {
    this.detail.id = this.$route.query.id;
    this.detail.isDetail = !!this.$route.query.id;
    if (this.detail.isDetail) {
      // 获取详情
      this.getOrderDetailById();
    }
    if (!this.detail.isDetail) {
      this.getSCMList();
    }
  },
  methods: {
    async getSCMList() {
      const res = await getSCMList();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data.list;
      }
    },
    async getOrderDetailById() {
      const res = await getInboundRecordDetail({ id: this.detail.id });
      if (res.code === 200) {
        console.log(res.data);
        this.formData.tableData = res.data.detailsList;
        this.sform.supplierId = res.data.supplierId;
        this.sform.remake = res.data.remake;
        this.sform.takeRemake = res.data.takeRemake;
        this.sform.warehouseName = res.data.warehouseName;
        this.sform.number = res.data.number;
        this.sform.supplierName = res.data.supplierName;
        // this.sform.remake = res.data.remake
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.selected = {};
          this.radio = "";
          console.log('this.sform.supplierId', this.sform.supplierId);
          const res = await getReceivingOrderListBySupplier({
            supplierId: this.sform.supplierId,
          });
          if (res.code === 200) {
            this.gridData1 = res.data;
            console.log(this.gridData1, "gridData");
          }
          this.dialogTableVisible = true;
        } else {
          this.$message.warning("请先选择供应商");
          return false;
        }
      });
    },
    submitData(formName) {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.formData.tableData.length <= 0)
            return this.$message.warning("请先选择订单");
          this.$refs.formData.validate(async (valid) => {
            if (valid) {
              console.log(this.formData, "formData");
              this.sform.detailsList = [];
              this.formData.tableData.forEach((item) => {
                this.sform.detailsList.push({
                  takeDetailsId: item.id,
                  positionId: item.positionId,
                  regionId: item.regionId,
                });
              });
              console.log(this.sform, "this.sform");
              const res = await addInboundRecord({ ...this.sform });
              if (res.code === 200) {
                this.$message.success("添加成功");
                this.closeTag("receiving");
              } else {
                // this.$message.error(res.message);
              }
            }
          });
        }
      });
    },
    supplierChange() {
      this.gridData2 = [];
      this.formData.tableData = [];
      this.formData.buyRemake = "";
      this.formData.warehouseName = "";
      this.sform.buyRemake = "";
      this.sform.warehouseName = "";
      this.formData.warehouseId = "";
      this.sform.warehouseId = "";
      this.selected = {};
      this.radio = "";
    },
    confirmFn() {
      this.formData.tableData = [];
      this.gridData2.forEach((item) => {
        this.formData.tableData.push(item);
      });
      this.sform.takeRemake = this.formData.takeRemake;
      this.sform.warehouseName = this.formData.warehouseName;
      this.sform.warehouseId = this.formData.warehouseId;
      this.gridData2 = [];
      this.dialogTableVisible = false;
    },
    cancelFn() {
      this.dialogTableVisible = false;
      this.selected = {};
      this.radio = "";
    },
    async showRow(row) {
      if (row) {
        // 赋值给radio
        this.radio = this.gridData1.indexOf(row);
        this.selected = row;
        console.log(this.selected, 'gggggg');
        this.sform.buyOrderId = row.id;
        const res = await selectDeliveryDetails({
          id: row.id,
          warehouseId: row.warehouseId,
        });
        if (res.code === 200) {
          this.gridData2 = res.data.detailsList;
          this.formData.takeRemake = res.data.remake;
          this.formData.warehouseName = res.data.warehouseName;
          this.formData.warehouseId = res.data.warehouseId;
          this.sform.takeDeliveryId = res.data.id;
          console.log(this.formData.takeRemake, "备注");
          console.log(this.sform.takeDeliveryId, "takeDeliveryId");
        } else {
          // this.$message.warning(res.data.message);
        }
        console.log(res.data, "详情");
      }
    },
    cancelBtn() {
      this.closeTag("receiving");
    },
    async getPositonList(row, index) {
      // console.log(row, 'row')
      console.log("获取列表");
      // if (this.formData.tableData[index].positionList) return
      if (!row.regionId)
        return this.$message.warning("该商品没有绑定区域，请先绑定区域");
      const res = await selectForInbound({
        warehouseId: this.sform.warehouseId,
        regionId: row.regionId,
      });
      if (res.code === 200) {
        let arr = res.data;
        arr = arr.filter(
          (item1) =>
            !this.disabledList.some(
              (item) =>
                item === item1.id &&
                item1.id !== this.formData.tableData[index].positionId
            )
        );
        if (arr.length <= 0)
          this.$message.warning("该区域没有仓位了，请先创建仓位");
        // if (this.formData.tableData[index].positionList)
        this.$set(this.formData.tableData[index], "positionList", arr);
        console.log(
          this.formData.tableData[index].positionList,
          "this.positionList"
        );
      }
    },
    selectPositionId(row, index) {
      // console.log(row.positionId, 'val')
      console.log("调用了");
      const selId = row.positionId;
      // this.disabledList =
      const arr = this.formData.tableData
        .filter((item) => {
          return item.positionId;
        })
        .map((item) => item.positionId);
      this.disabledList = [...new Set(arr)];
      console.log(this.disabledList, "this.disabledList");
      const flag = this.formData.tableData.some(
        (item, inx) => item.positionId === selId && inx !== index
      );
      if (flag) {
        //
        this.$message.warning("该仓位已被选择");
        this.$set(this.formData.tableData[index], "positionId", "");
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.flexContent {
  h3 {
    margin: 0;
    margin-bottom: 10px;
  }
}</style>
